const {
	exec,
	execFile,
	fork,
	spawn,
} = require('child_process');
const crypto = require('crypto');
const {
	ObjectID,
} = require('mongodb')
const numCPUs = require('os').cpus().length;
const Response = require('./Response')
const {
	getTime,
} = require('../utils/dateUtils')
const {
	sleep,
} = require('../utils')
const {
	_crawlerMongo,
} = global

module.exports = {

	/**
	 * 资源分类列表
	 * @param  {[type]} params [description]
	 * @return {[type]}        [description]
	 */
	menu: async function() {
		let taskCol = await _crawlerMongo.getCollection('task')
		let artistSource = taskCol.distinct('source', {
			_type_: 'artist'
		})
		let type = taskCol.distinct('_type_', {
			'_type_.id': {
				$exists: true
			}
		})
		let result = await Promise.all([artistSource, type])
		let typeArr = result[1]
		let menulist = []
		for (let i = 0; i < typeArr.length; i++) {
			let type = typeArr[i]
			let cateArr = await taskCol.distinct('_cate_', {
				'_type_.id': type.id,
			})
			menulist.push(Object.assign(type, {
				cate: cateArr,
			}))
		}
		return new Response('000', '成功', {
			docs: {
				artist: result[0] || [],
				menulist,
			},
		})
	},

	/**
	 * 资源列表
	 * @param  {[type]} params [description]
	 * @return {[type]}        [description]
	 */
	list: async function(params) {
		let {
			cateId,
			typeId,
			status,
			pn = 1,
			ps = 10,
		} = params
		let skip = (pn - 1) * ps
		let query = {
			'_cate_.id': cateId,
			'_type_.id': typeId,
		}
		let taskCol = await _crawlerMongo.getCollection('task')
		let amount = taskCol.count(query)
		query.status = 1
		let runningCount = taskCol.count(query)
		query.status = 2
		let stopCount = taskCol.count(query)
		query.status = -1
		let successCount = taskCol.count(query)
		query.status = 0
		let waitingCount = taskCol.count(query)
		query.status = status
		if (status == 100)
			delete query.status
		let sort = {
			modify_time: -1,
		}
		if (query.status == 1)
			sort = {
				create_time: 1,
			}
		let total = taskCol.count(query)
		let docs = taskCol.find(query).sort(sort).skip(skip).limit(ps).toArray()
		let result = await Promise.all([total, docs, runningCount, stopCount, successCount, waitingCount, amount])
		return new Response('000', '成功', {
			total: result[0],
			docs: result[1],
			isrunning: result[2] > 0,
			runningCount: result[2],
			stopCount: result[3],
			successCount: result[4],
			waitingCount: result[5],
			amount: result[6],
		})
	},

	// artist: async function(params) {
	// 	let {
	// 		_type_,
	// 		source,
	// 		pn = 1,
	// 		ps = 30,
	// 		status,
	// 	} = params
	// 	let skip = (pn - 1) * ps
	// 	let query = {
	// 		source,
	// 		_type_: 'artist',
	// 	}
	// 	query.status = 1
	// 	let taskCol = await _crawlerMongo.getCollection('task')
	// 	let runningCount = await taskCol.count(query)
	// 	query.status = status
	// 	if (status == 100)
	// 		delete query.status
	// 	let total = await taskCol.count(query)
	// 	let docs = await taskCol.find(query).sort({
	// 		task_id: 1
	// 	}).skip(skip).limit(ps).toArray()
	// 	return new Response('000', '成功', {
	// 		total,
	// 		docs,
	// 		isrunning: runningCount > 0
	// 	})
	// },

	start: async function(params) {
		let {
			_id,
			cateId,
			typeId,
		} = params
		let query = {
			'_cate_.id': cateId,
			'_type_.id': typeId,
		}
		let taskCol = await _crawlerMongo.getCollection('task')
		if (_id) {
			let task = await taskCol.findOne({
				_id: ObjectID(_id)
			})
			startChildProcess(task._bash_, {
				_id,
			})
		} else {
			let task = await taskCol.findOne(query)
			console.log('numCPUs', numCPUs)
			for (let i = 0; i < 3; i++) {
				console.log(i, 'task._bash_', task._bash_)
				startChildProcess(task._bash_, {
					idx: i,
				}, true)
				await sleep(500)
			}
		}
		return new Response('000', '成功', 'success')
	},

	isrunning: async function(params) {
		let {
			_id,
			source,
		} = params
		let taskCol = await _crawlerMongo.getCollection('task')
		let query = {
			source,
			_type_: 'artist',
			status: 1,
		}
		if (_id)
			query._id = ObjectID(_id)
		let count = await taskCol.count(query)
		return new Response('000', '成功', {
			isrunning: count > 0
		})
	},

	clear: async function() {

	},

	goon: async function() {

	},

}

/**
 * 密码加密
 * @param  {[type]} password [description]
 * @return {[type]}          [description]
 */
function encPwd(password) {
	return crypto.createHash('md5').update(password).digest('hex');
}

function startChildProcess(bash, vals, mult) {
	let {
		cmd,
		args = [],
		params,
		options = {},
		child_process,
	} = bash
	if (mult === true && typeof vals.idx == 'number') {
		cmd = cmd.replace('#{_id}.log', `${vals.idx}.log`)
	}
	for (let key in params) {
		let val = vals && vals[parseParams(key)] || params[key] || ''
		cmd = cmd.replace(new RegExp(key, 'g'), val)
	}
	if (child_process == 'exec') {
		exec(cmd, options)
	}
	if (child_process == 'fork') {
		fork(cmd, args, options)
	}
}

function parseParams(val = '') {
	return val && val.replace(/^#{|}$/g, '').trim() || ''
}